package com.psy.counseling.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psy.counseling.service.QuestionService;
import com.psy.counseling.service.UserService;
import com.psy.counseling.utils.Result;
import com.psy.counseling.entity.Question;
import com.psy.counseling.entity.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
 * <p>
 *  试题管理的增删改查以及导入导出
 * </p>
 *
 * @author 陈灿
 * @since 2022-05-31
 */
@RestController
@RequestMapping("/api/question")
public class QuestionController {

    @Resource
    private QuestionService questionService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserService userService;


    public User getUser() {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getAudience().get(0);
        return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }
    @PostMapping
    public Result<?> save(@RequestBody Question question) {
        questionService.save(question);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Question question) {
        questionService.updateById(question);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        questionService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(questionService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        List<Question> list = questionService.list();
        return Result.success(list);
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String info,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Question> query = Wrappers.<Question>lambdaQuery().orderByDesc(Question::getId);
        if (StrUtil.isNotBlank(info)) {
            query.like(Question::getQuestionInfo, info);
        }
        IPage<Question> page = questionService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }
    /*    @GetMapping("/page")
        public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                  @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                  @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
            LambdaQueryWrapper<Song> query = Wrappers.<Song>lambdaQuery().orderByDesc(Song::getId);
            if (StrUtil.isNotBlank(name)) {
                query.like(Song::getName, name);
            }
            IPage<Song> page = songService.page(new Page<>(pageNum, pageSize), query);
            return Result.success(page);
        }*/
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = CollUtil.newArrayList();

        List<Question> all = questionService.list();
        for (Question obj : all) {
            Map<String, Object> row = new LinkedHashMap<>();
            row.put("id", obj.getId());
            row.put("题目描述", obj.getQuestionInfo());
            row.put("选项A", obj.getAOption());
            row.put("选项B", obj.getBOption());
            row.put("选项C", obj.getCOption());
            row.put("选项D", obj.getDOption());
            row.put("选项A权值", obj.getAWeight());
            row.put("选项B权值", obj.getBWeight());
            row.put("选项C权值", obj.getCWeight());
            row.put("选项D权值", obj.getDWeight());

            list.add(row);
        }

        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("题目信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }

    @PostMapping("/importQuestions")
    public Result<?> importUsers(MultipartFile multipartFile) throws IOException {
        ArrayList<Integer> errorList = questionService.importQuestions(multipartFile);
        errorList.forEach(System.out::println);
        return Result.success(errorList);
    }
    @GetMapping("/upload/{fileId}")
    public Result<?> upload(@PathVariable String fileId) {
        String basePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
        List<String> fileNames = FileUtil.listFileNames(basePath);
        String file = fileNames.stream().filter(name -> name.contains(fileId)).findAny().orElse("");
        List<List<Object>> lists = ExcelUtil.getReader(basePath + file).read(1);
        List<Question> saveList = new ArrayList<>();
        for (List<Object> row : lists) {
            Question obj = new Question();
            obj.setQuestionInfo((String) row.get(1));
            obj.setAOption((String) row.get(2));
            obj.setBOption((String) row.get(3));
            obj.setCOption((String) row.get(4));
            obj.setDOption((String) row.get(5));
            obj.setAWeight((Integer) row.get(6));
            obj.setBWeight((Integer) row.get(7));
            obj.setCWeight((Integer) row.get(8));
            obj.setDWeight((Integer) row.get(9));

            saveList.add(obj);
        }
        questionService.saveBatch(saveList);
        return Result.success();
    }
}
